package com.xhx.api.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 全局过滤器
 * 解决跨域请求头问题
 */
@Order(Ordered.HIGHEST_PRECEDENCE) // 数越小，优先级最高
@Configuration
public class CorsFilterConfig implements Filter {

    /**
     * 该方法用于初始化过滤器
     */
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    /**
     * 该方法在容器移除 servlet 时执行，同样只执行一次
     */
    @Override
    public void destroy() {
    }

    /**
     * 只执行在响应 WEB 请求的最开始
     * 跨域 过滤器
     *
     * @param servletRequest  请求
     * @param servletResponse 输出
     * @param filterChain     过滤
     * @throws IOException      IO异常
     * @throws ServletException Servlet异常
     */
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        // 强转
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        response.setHeader("Access-Control-Allow-Origin", "*"); // 请求域名 http://localhost:8081
        response.setHeader("Access-Control-Allow-Headers", "*"); // 请求header访问
        response.setHeader("Access-Control-Allow-Methods", "*");  // 请求方法
        response.setHeader("Access-Control-Allow-Credentials", "true"); // 允许发送 Cookie
        response.setHeader("Access-Control-Allow-Max-Age", "7200"); // 预检请求有效时间

        // 放行 OPTIONS
        if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
            response.setStatus(HttpServletResponse.SC_OK);
        } else {
            // 执行过滤
            filterChain.doFilter(servletRequest, servletResponse);
        }
    }
}